package org.mspring.mlog.web.module.web.widget;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.common.Keys;
import org.mspring.mlog.entity.Comment;
import org.mspring.mlog.service.CommentService;
import org.mspring.platform.utils.CookieUtils;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 
 * @author Gao Youbo
 * @since 2013年9月23日
 */
@Widget
@RequestMapping("/widget/comment")
public class Widget_CommentWidget extends Widget_AbstractWidget {
    @Autowired
    private CommentService commentService;

    /**
     * 最新评论
     * 
     * @param tpl
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/recent")
    public String recent(@RequestParam(required = false, defaultValue = "/widget/comment/recent") String tpl, HttpServletRequest request, HttpServletResponse response, Model model) {
        Integer num = RequestUtils.getRequestParameterAsInteger(request, "num");
        if (num == null) {
            num = 10;
        }
        List<Comment> comments = commentService.recent(num);
        model.addAttribute("comments", comments);
        return "skin:" + tpl;
    }

    /**
     * 文章对应的评论
     * 
     * @param tpl
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/postComments")
    public String postComments(@RequestParam(required = false, defaultValue = "/widget/comment/postComments") String tpl, HttpServletRequest request, HttpServletResponse response, Model model) {
        Long post = RequestUtils.getRequestParameterAsLong(request, "post");
        List<Comment> comments = commentService.findCommentsByPost(post);
        model.addAttribute("comments", comments);
        model.addAttribute("postId", post);
        model.addAttribute("author", CookieUtils.getCookie(request, Keys.COMMENT_AUTHOR_COOKIE));
        model.addAttribute("email", CookieUtils.getCookie(request, Keys.COMMENT_EMAIL_COOKIE));
        model.addAttribute("url", CookieUtils.getCookie(request, Keys.COMMENT_URL_COOKIE));
        return "skin:" + tpl;
    }
}
